from flask import g
from flask import render_template, current_app, jsonify
from flask import request
from flask import session

from info import constants
from info.models import User, Category, News
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info import redis_store


# 参数：页码/分类ID/每页数量
@index_blue.route('/news_list')
def news_list():
    # 一. 获取参数（可选，可以给默认值）
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    # 二. 校验参数（验证数据类型）
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 三. 逻辑处理
    # 方式一：
    # if cid ==1:
    #     News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    # else:
    #     News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page, per_page, False)

    # filters = {}
    # if cid != 1:
    #     filters["category_id"] = cid
    #
    # try:
    #     paninates = News.query.filter_by(**filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    # 方式二：

    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)

    try:
        paninates = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    # 获取的所有新闻模型数据
    news_mobile = paninates.items

    # 为了方便前端判断是否有下一页可以加载，我们通常会返回当前页码和总页码
    # 获取分也的总页码
    total_page = paninates.pages

    # 获取当前页码
    current_page = paninates.page

    news_list = []
    for news in news_mobile if news_mobile else []:
        news_list.append(news.to_basic_dict())
    # 四. 返回数据
    data = {
        'news_list': news_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg='成功', data=data)


@index_blue.route('/')
@user_login_data
def index():
    # # 在这里登陆， 再次调用，我们就可以根据session数据，获取用户信息
    #
    # # 一. 获取用户数据
    # # 读取session数据
    # user_id = session.get('user_id')
    # # 通过id获取用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 一.获取用户数据
    user = g.user

    # 二. 分类数据, 查询后转字典返回
    categorys = None
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    categorys_list = []
    for category in categorys if categorys else []:
        categorys_list.append(category.to_dict())

    # 三. 点击排行，查询后转字典
    try:
        news_models = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 拼接返回数据字典
    click_news_list = []
    for news in news_models if news_models else []:
        click_news_list.append(news.to_basic_dict())

    data = {
        # 为了方便返回所需要的数据，我们开发中一般会定义to_dict函数
        # user有值，就返回前面的数据，没有值，就返回None——> 末班就解析不出来数据
        # 模型转字典
        'user': user.to_dict() if user else None,
        'categorys_list': categorys_list,
        'click_news_list': click_news_list

    }

    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
